/*
 * Copyright (c) 2018-2999 北京小象智慧信息科技有限公司 All rights reserved.
 *
 * https://www.xiaoxiangai.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.sys.service.impl;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.model.*;
import com.yami.shop.dao.ProdCategoryMapper;
import com.yami.shop.service.*;
import com.yami.shop.service.SmsLogService;
import com.yami.shop.sys.dao.SysUserMapper;
import com.yami.shop.sys.dao.SysUserRoleMapper;
import com.yami.shop.sys.dto.UserAndShopDto;
import com.yami.shop.sys.model.SysUser;
import com.yami.shop.sys.model.SysUserRole;
import com.yami.shop.sys.service.SysUserService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 系统用户
 * @author lgh
 */
@Service("sysUserService")
@AllArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

	private SysUserRoleMapper sysUserRoleMapper;

	private SysUserMapper sysUserMapper;

	@Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private ShopDetailService shopDetailService;
    @Autowired
    private ProductService productService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SkuService skuService;
    @Autowired
    private ProdCategoryService prodCategoryService;
	@Autowired
	private SmsLogService smsLogService;
    @Autowired
    private ProdCategoryMapper prodCategoryMapper;


	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveUserAndUserRole(SysUser user) {
		user.setCreateTime(new Date());
		sysUserMapper.insert(user);
		if(CollUtil.isEmpty(user.getRoleIdList())){
			return ;
		}
		//保存用户与角色关系
		sysUserRoleMapper.insertUserAndUserRole(user.getUserId(), user.getRoleIdList());
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateUserAndUserRole(SysUser user) {
		// 更新用户
		sysUserMapper.updateById(user);

		//先删除用户与角色关系
		sysUserRoleMapper.deleteByUserId(user.getUserId());

		if(CollUtil.isEmpty(user.getRoleIdList())){
			return ;
		}
		//保存用户与角色关系
		sysUserRoleMapper.insertUserAndUserRole(user.getUserId(), user.getRoleIdList());
	}

	@Override
	public void updatePasswordByUserId(Long userId, String newPassword) {
        SysUser user = new SysUser();
        user.setPassword(newPassword);
        user.setUserId(userId);
        sysUserMapper.updateById(user);
    }

	@Override
	public void updatePasswordByPhone(String username,String phone, String newPassword) {
		SysUser user = new SysUser();
		user.setPassword(newPassword);
		user.setMobile(phone);
		user.setUsername(username);
		sysUserMapper.updatePasswordByPhone(username,phone,newPassword);
	}

	@Override
    @Transactional(rollbackFor = Exception.class)
	public void deleteBatch(Long[] userIds) {

		for(int i =0;i<userIds.length;i++){
			Long userId = userIds[i];
			sysUserRoleMapper.deleteByUserId(userId);
			SysUser sysUser = sysUserMapper.selectByUserId(userId);
			Long shopId = sysUser.getShopId();
			categoryService.deleteCategroyByShopId(shopId);
			shopDetailService.deleteShopDetailByShopId(shopId);
			List<Product> product = productService.selectProductByShopId(shopId);
            for (int j = 0; j < product.size(); j++) {
                Long prodId = product.get(j).getProdId();
                prodCategoryMapper.deleteByProdId(prodId);
                skuService.deleteSkuByProdId(prodId);
            }
            productService.deleteProductByShopId(shopId);
        }
		sysUserMapper.deleteBatch(userIds);
	}

	@Override
	public SysUser getByUserName(String username) {
		return sysUserMapper.selectByUsername(username);
	}

    @Override
    public List<SysUser> selectByMobile(String mobile) {
        return sysUserMapper.selectByMobile(mobile);
    }

	@Override
	public List<SysUser> checkUserByUserName(String username) {
		return sysUserMapper.checkUserByUserName(username);
	}

	@Override
	public SysUser getSysUserById(Long userId) {
		return sysUserMapper.selectById(userId);
	}

	@Override
	public UserAndShopDto getSysUserByUserId(Long userId) {
		return sysUserMapper.getSysUserByUserId(userId);
	}

	/**
	 * 查询数据库中最大的shopId
	 */
	@Override
	public Integer selectMaxShopId(){
	    return sysUserMapper.selectMaxShopId();
    }

	/**
	 * 根据shopId查询userId
	 */
	@Override
	public SysUser getSysUserId(Long shopId){
		return sysUserMapper.getSysUserId(shopId);
	}

	/**
	 * 商家入驻
	 * @param userAndShop
	 */
	@Override
    @Transactional(rollbackFor = Exception.class)
	public String toSave(UserAndShop userAndShop) {
		SysUser sysUser = new SysUser();
		String username = userAndShop.getUsername();
		sysUser.setUsername(username);
		sysUser.setStatus(1);
		sysUser.setState(1);
		sysUser.setMobile(userAndShop.getMobile());
		sysUser.setPassword(passwordEncoder.encode(userAndShop.getPassword()));
		ShopDetail shopDetail = new ShopDetail();
		shopDetail.setShopOwner(userAndShop.getShopOwner());
		shopDetail.setMobile(userAndShop.getMobile());
		shopDetail.setShopName(userAndShop.getShopName());
		shopDetail.setIdCard(userAndShop.getIdCard());
		shopDetail.setBussinessLicense(userAndShop.getBussinessLicense());
		shopDetail.setState(1);
		shopDetail.setShopStatus(-1);
		shopDetail.setProvince(userAndShop.getProvince());
		shopDetail.setCity(userAndShop.getCity());
		shopDetail.setArea(userAndShop.getArea());
		shopDetail.setShopAddress(userAndShop.getShopAddress());
		shopDetail.setShopLng(userAndShop.getShopLng());
		shopDetail.setShopLat(userAndShop.getShopLat());
		shopDetail.setCreateTime(new Date());
		shopDetail.setOpenTime("08:00:00-22:00:00");
		shopDetail.setHygienicLicense(userAndShop.getHygienicLicense());
		shopDetail.setFoodBusinessLicense(userAndShop.getFoodBusinessLicense());
		shopDetailService.save(shopDetail);
		sysUser.setShopId(shopDetail.getShopId());
		sysUserMapper.insert(sysUser);
		return "success";
	}

    /**
     * 商家入驻审核
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateShopState(ShopDetail shopDetail) {
        Integer state = shopDetail.getState();
        Long shopId = shopDetail.getShopId();
        ShopDetail newShopDetail = shopDetailService.getShopDetailByShopId(shopId);
        shopDetail.setShopId(shopDetail.getShopId());
        shopDetail.setState(shopDetail.getState());
        shopDetail.setMeituanDistributionFlag(newShopDetail.getMeituanDistributionFlag());
        shopDetail.setMainStore(newShopDetail.getMainStore());
        if(state!=null&&state==0){
        	shopDetail.setShopStatus(1);
		}
        shopDetail.setAgentId(shopDetail.getAgentId());
        shopDetail.setUpdateTime(new Date());
        shopDetailService.saveOrUpdate(shopDetail);
        SysUser sysUser = sysUserMapper.getSysUserId(shopDetail.getShopId());
        //更新user表中的审核状态
        sysUser.setState(state);
        sysUserMapper.updateById(sysUser);
        if(state!=null&&state==0){
            /**
             * 为新注册审核通过商家添加分类
             */
            List<Category> categoryList = categoryService.getAllCategory(1L);
			if(categoryList.size()>0){
				for(Category category:categoryList){
					category.setCategoryId(null);
					category.setShopId(shopId);
					categoryService.save(category);
				}
			}
//            Category category = new Category();
//            category.setShopId(shopId);
//            category.setParentId(0L);
//            category.setCategoryName("店铺招牌");
//            category.setSeq(1);
//            category.setStatus(1);
//            category.setRecTime(new Date());
//            category.setGrade(0);
//            list.add(category);
//            Category category1 = new Category();
//            category1.setShopId(shopId);
//            category1.setParentId(0L);
//            category1.setCategoryName("新品推荐");
//            category1.setSeq(2);
//            category1.setStatus(1);
//            category1.setRecTime(new Date());
//            category1.setGrade(0);
//            list.add(category1);
//			Category category2 = new Category();
//            category2.setShopId(shopId);
//            category2.setParentId(0L);
//            category2.setCategoryName("活动专区");
//            category2.setSeq(3);
//            category2.setStatus(1);
//            category2.setRecTime(new Date());
//            category2.setGrade(0);
//			list.add(category2);
//            for(int i = 0;i<list.size();i++){
//                categoryService.saveCategroy(list.get(i));
//            }
            /**
             * 自动给新注册审核通过的商家匹配产品
             */
            List<Product> productList = productService.getAllProduct(1L);
            if(productList.size()>0&&productList!=null){
                for (int i=0;i<productList.size();i++){
                    Product product = productList.get(i);
                    Long prodId = product.getProdId();
                    product.setShopId(shopId);
                    product.setStatus(1);
                    product.setSoldNum(0);
                    product.setTotalStocks(1000);
                    productService.save(product);
                    Sku sku = new Sku();
                    sku = skuService.getSkuByProdId(prodId);
                    sku.setProdId(product.getProdId());
//                    sku.setOriPrice(product.getOriPrice());
//                    sku.setPrice(product.getPrice());
                    sku.setStocks(1000);
                    sku.setUpdateTime(new Date());
                    sku.setRecTime(new Date());
//                    sku.setProdName(product.getProdName());
                    sku.setIsDelete(0);
                    skuService.save(sku);
                    List<ProdCategory> prodCategoryList = prodCategoryService.listByProdId(prodId);
                    List<Long> categoryIdList = categoryService.getAllCategoryId(prodId);
//                    prodCategory.setProdId(product.getProdId());
//                    prodCategory.setCategoryId(category.getCategoryId());
//                    prodCategoryService.save(prodCategory);
                    if(categoryIdList.size()>0){
                        for(Long categoryId:categoryIdList){
                            Category category = categoryService.getById(categoryId);
                            String categoryName = category.getCategoryName();
                            Long caId = categoryService.getCategoryId(shopId,categoryName);
                            ProdCategory prodCategory = new ProdCategory();
                            prodCategory.setProdId(product.getProdId());
                            prodCategory.setCategoryId(caId);
                            prodCategoryService.save(prodCategory);
                        }
                    }
                }
            }

            /**
             * 为新注册审核通过商家开通权限
             */

            Long userId = sysUser.getUserId();
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(userId);
            sysUserRole.setRoleId(2L);
            sysUserRoleMapper.insert(sysUserRole);

			/**
			 * 通过审核,短信通知商家
			 */
			ShopDetail shopDetail1 = shopDetailService.getShopDetailByShopId(shopDetail.getShopId());
			String mobile =  shopDetail1.getMobile();
			smsLogService.sendSmsAfterPassing(mobile);
        }
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public String saveBranchShop(UserAndShop userAndShop) {
		SysUser sysUser = new SysUser();
		SysUser oldUser =  sysUserMapper.getSysUser(Long.valueOf(userAndShop.getMainStore()));
		String username = userAndShop.getUsername();
		sysUser.setUsername(oldUser.getUsername()+Math.random() * 100);
		sysUser.setPassword(oldUser.getPassword());
		sysUser.setStatus(1);
		sysUser.setState(1);
		sysUser.setMobile(userAndShop.getMobile());
		ShopDetail shopDetail = new ShopDetail();
		shopDetail.setShopOwner(userAndShop.getShopOwner());
		shopDetail.setMobile(userAndShop.getMobile());
		shopDetail.setShopName(userAndShop.getShopName());
		shopDetail.setIdCard(userAndShop.getIdCard());
		shopDetail.setBussinessLicense(userAndShop.getBussinessLicense());
		shopDetail.setState(1);
		shopDetail.setShopStatus(-1);
		shopDetail.setProvince(userAndShop.getProvince());
		shopDetail.setCity(userAndShop.getCity());
		shopDetail.setArea(userAndShop.getArea());
		shopDetail.setShopAddress(userAndShop.getShopAddress());
		shopDetail.setShopLng(userAndShop.getShopLng());
		shopDetail.setShopLat(userAndShop.getShopLat());
		shopDetail.setCreateTime(new Date());
		shopDetail.setOpenTime("08:00:00-22:00:00");
		shopDetail.setHygienicLicense(userAndShop.getHygienicLicense());
		shopDetail.setMainStore(userAndShop.getMainStore());
		shopDetail.setFoodBusinessLicense(userAndShop.getFoodBusinessLicense());
		shopDetailService.save(shopDetail);
		sysUser.setShopId(shopDetail.getShopId());
		sysUserMapper.insert(sysUser);
		return "success";
	}

	@Override
	public SysUser getSysUser(Long shopId) {
		return sysUserMapper.getSysUser(shopId);
	}

}
